<template>
  <div class="countdown-page">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <div class="header-left">
            <el-button @click="$router.push('/dashboard')" icon="ArrowLeft" class="back-btn">
              返回
            </el-button>
          </div>
          <div class="header-center">
            <div class="page-title">
              <el-icon class="title-icon"><Clock /></el-icon>
              <h2>倒计时</h2>
            </div>
          </div>
          <div class="header-right">
            <div class="countdown-status">
              <el-tag v-if="isRunning" type="success" :disable-transitions="true" class="status-tag">运行中</el-tag>
              <el-tag v-else type="warning" :disable-transitions="true" class="status-tag">已停止</el-tag>
            </div>
          </div>
        </div>
      </el-header>
      
      <el-main class="main">
        <el-card class="countdown-card">
          <div class="countdown-display">
            <div class="time-display">{{ formatTime(displayTime) }}</div>
            <div class="duration-selector">
              <el-select v-model="selectedDuration" placeholder="选择倒计时时长" size="large">
                <el-option label="1分钟" :value="60" />
                <el-option label="3分钟" :value="180" />
                <el-option label="5分钟" :value="300" />
                <el-option label="10分钟" :value="600" />
                <el-option label="20分钟" :value="1200" />
                <el-option label="30分钟" :value="1800" />
                <el-option label="1小时" :value="3600" />
                <el-option label="2小时" :value="7200" />
              </el-select>
            </div>
            <div class="countdown-controls">
              <el-button 
                v-if="!isRunning && !isPaused" 
                type="primary" 
                size="large"
                @click="startCountdown"
                :disabled="!selectedDuration"
                :icon="VideoPlay"
              >
                开始
              </el-button>
              <el-button 
                v-else-if="isRunning" 
                type="warning" 
                size="large"
                @click="pauseCountdown"
                :icon="VideoPause"
              >
                暂停
              </el-button>
              <el-button 
                v-else-if="isPaused" 
                type="success" 
                size="large"
                @click="resumeCountdown"
                :icon="VideoPlay"
              >
                继续
              </el-button>
              <el-button 
                type="danger" 
                size="large"
                @click="stopCountdown"
                 :icon="Close"
              >
                停止
              </el-button>
              <el-button 
                type="info" 
                size="large"
                @click="resetCountdown"
                :icon="Refresh"
              >
                重置
              </el-button>
            </div>
          </div>
        </el-card>
        
        <!-- 通知设置卡片 -->
        <el-card class="notification-card">
          <template #header>
            <div class="card-header" @click="toggleNotificationSettings">
              <div class="header-left">
                <el-icon class="header-icon" :class="{ 'rotated': !notificationSettingsExpanded }">
                  <ArrowDown v-if="notificationSettingsExpanded" />
                  <ArrowRight v-else />
                </el-icon>
                <h4>通知设置</h4>
              </div>
              <div class="header-controls">
                <el-switch 
                  v-model="notificationEnabled" 
                  active-text="启用通知" 
                  inactive-text="禁用通知"
                  class="notification-switch"
                  @click.stop
                />
                <el-tag v-if="settingsChanged" type="warning" size="small" class="settings-status">
                  <el-icon><Edit /></el-icon>
                  设置已修改
                </el-tag>
                <el-tag v-else type="success" size="small" class="settings-status">
                  <el-icon><Check /></el-icon>
                  设置已保存
                </el-tag>
              </div>
            </div>
          </template>
          <div class="notification-settings" v-show="notificationSettingsExpanded" v-if="notificationEnabled">
            <!-- 铃声选择 -->
            <div class="setting-section">
              <div class="section-title">
                <el-icon class="section-icon"><Headset /></el-icon>
                <span>铃声设置</span>
              </div>
              <div class="setting-item">
                <label>铃声选择：</label>
                <el-select v-model="selectedSound" placeholder="选择铃声" class="sound-select">
                  <el-option label="🎵 卡农铃声" value="kanong" />
                  <el-option label="🎵 In Love With a Ghost" value="in_love_with_a_ghost" />
                  <el-option label="🎵 山下智久-Loveless" value="loveless" />
                  <el-option label="🎵 Thomas Greenberg-Clear as Day" value="clear_as_day" />
                  <el-option label="🎵 Shayne Ward-Save Me" value="save_me" />
                  <el-option label="🎵 Said The Sky-Listen" value="listen" />
                  <el-option label="🎵 代号鸢-刘辩哼唧" value="liubian" />
                  <el-option label="🎵 罗晨渝-QQ提示音" value="qq_tone" />
                  <el-option label="🔇 无声音" value="none" />
                </el-select>
              </div>
              <div class="setting-item">
                <label>音量控制：</label>
                <div class="volume-control">
                  <el-slider 
                    v-model="volume" 
                    :min="0" 
                    :max="100" 
                    :step="10"
                    class="volume-slider"
                    show-stops
                    :show-tooltip="false"
                  />
                  <div class="volume-display">
                    <!-- <el-icon v-if="volume === 0"><Mute /></el-icon>
                    <el-icon v-else-if="volume <= 30"><Minus /></el-icon>
                    <el-icon v-else-if="volume <= 70"><Microphone /></el-icon>
                    <el-icon v-else><Plus /></el-icon> -->
                    <span class="volume-text">{{ volume }}%</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 通知选项 -->
            <div class="setting-section">
              <div class="section-title">
                <el-icon class="section-icon"><Notification /></el-icon>
                <span>通知选项</span>
              </div>
              <div class="checkbox-group">
                <el-checkbox v-model="vibrationEnabled" class="feature-checkbox">
                  <el-icon class="checkbox-icon"><BellFilled /></el-icon>
                  启用振动(仅支持app)
                </el-checkbox>
                <el-checkbox v-model="browserNotificationEnabled" class="feature-checkbox">
                  <el-icon class="checkbox-icon"><Message /></el-icon>
                  浏览器通知
                </el-checkbox>
                <el-checkbox v-model="requireConfirmation" class="feature-checkbox">
                  <el-icon class="checkbox-icon"><QuestionFilled /></el-icon>
                  需要确认才停止铃声
                </el-checkbox>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="setting-section">
              <div class="section-title">
                <el-icon class="section-icon"><Tools /></el-icon>
                <span>设置管理</span>
              </div>
              <div class="action-buttons">
                <div class="button-row">
                  <el-button @click="testNotification" type="primary" size="small" class="action-btn">
                    <el-icon><VideoPlay /></el-icon>
                    测试通知
                  </el-button>
                  <el-button @click="resetToDefaultSettings" type="warning" size="small" class="action-btn">
                    <el-icon><Refresh /></el-icon>
                    重置为默认
                  </el-button>
                </div>
                <div class="button-row">
                  <el-button @click="exportSettings" type="success" size="small" class="action-btn">
                    <el-icon><Download /></el-icon>
                    导出设置
                  </el-button>
                  <el-button @click="importSettings" type="info" size="small" class="action-btn">
                    <el-icon><Upload /></el-icon>
                    导入设置
                  </el-button>
                </div>
                <div class="button-row" v-if="settingsChanged">
                  <el-button @click="saveSettings" type="primary" size="small" class="action-btn">
                    <el-icon><Check /></el-icon>
                    保存设置
                  </el-button>
                  <el-button @click="cancelChanges" type="danger" size="small" class="action-btn">
                    <el-icon><Close /></el-icon>
                    取消更改
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-card>
        
        <el-card class="record-card">
          <template #header>
            <h4>记录管理</h4>
          </template>
          <div class="record-controls">
            <el-button 
              type="success" 
              @click="saveRecord"
              :loading="saving"
              :disabled="!hasRecordedTime"
              class="record-controls-btn"
            >
              保存记录
            </el-button>
            <el-button 
              type="info" 
              @click="loadTodayTotal"
              class="record-controls-btn"
            >
              查看今日总计
            </el-button>
          </div>
          <div v-if="todayTotal > 0" class="today-total">
            <span>今日总计：{{ formatTime(todayTotal) }}</span>
          </div>
        </el-card>
      </el-main>
    </el-container>
    
    <!-- 倒计时结束确认对话框 -->
    <el-dialog
      v-model="showCompletionDialog"
      title="倒计时结束"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      class="completion-dialog"
    >
      <div class="completion-content">
        <div class="completion-icon">
          <el-icon size="48" color="#67c23a"><Bell /></el-icon>
        </div>
        <div class="completion-message">
          <h3>倒计时已完成！</h3>
          <p>您设置的 {{ formatTime(selectedDuration) }} 倒计时已经结束</p>
        </div>
        <div class="completion-actions">
          <el-button 
            type="primary" 
            size="large"
            @click="confirmCompletion"
            :loading="saving"
          >
            确定并保存记录
          </el-button>
        </div>
      </div>
    </el-dialog>
    
    <!-- 悬浮主题切换按钮 -->

  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
// import axios from 'axios'
// 新写法（自动适配环境）
import request from '../utils/request'
import dayjs from 'dayjs'
// import { VideoPlay, VideoPause, VideoStop, Refresh } from '@element-plus/icons-vue'
// import { VideoPlay, VideoPause, Stop, Refresh } from '@element-plus/icons-vue'
import { VideoPlay, VideoPause, CircleClose, Close, Refresh, Clock, Bell, Edit, Check, Headset, Notification, Message, QuestionFilled, Tools, Download, Upload, Mute, Minus, Microphone, Plus, BellFilled, ArrowDown, ArrowRight } from '@element-plus/icons-vue'

const isRunning = ref(false)
const isPaused = ref(false)
const displayTime = ref(0)
const selectedDuration = ref(3600)
const recordedTime = ref(0)
const todayTotal = ref(0)
const saving = ref(false)

// 通知相关状态
const notificationEnabled = ref(true)
const selectedSound = ref('kanong')
const volume = ref(80)
const vibrationEnabled = ref(true)
const browserNotificationEnabled = ref(true)
const requireConfirmation = ref(true)

// 振动控制
const vibrationInterval = ref(null)
const isVibrating = ref(false)

// 设置状态跟踪
const settingsChanged = ref(false)
const originalSettings = ref(null)

// 通知设置卡片折叠/展开状态
const notificationSettingsExpanded = ref(false)

// 获取铃声显示标签
const getSoundLabel = (soundValue) => {
  const soundLabels = {
    'kanong': '卡农铃声',
    'in_love_with_a_ghost': 'In Love With a Ghost',
    'loveless': '山下智久-Loveless',
    'clear_as_day': 'Thomas Greenberg-Clear as Day',
    'save_me': 'Shayne Ward-Save Me',
    'listen': 'Said The Sky-Listen',
    'liubian': '代号鸢-刘辩哼唧',
    'qq_tone': '罗晨渝-QQ提示音',
    'none': '无声音'
  }
  return soundLabels[soundValue] || soundValue
}

// 默认通知设置
const defaultSettings = {
  notificationEnabled: true,
  selectedSound: 'kanong',
  volume: 80,
  vibrationEnabled: true,
  browserNotificationEnabled: true,
  requireConfirmation: true
}

// 检查设置是否发生变化
const checkSettingsChanged = () => {
  if (!originalSettings.value) return false
  
  const currentSettings = JSON.stringify({
    notificationEnabled: notificationEnabled.value,
    selectedSound: selectedSound.value,
    volume: volume.value,
    vibrationEnabled: vibrationEnabled.value,
    browserNotificationEnabled: browserNotificationEnabled.value,
    requireConfirmation: requireConfirmation.value
  })
  
  settingsChanged.value = currentSettings !== originalSettings.value
  return settingsChanged.value
}

// 保存设置到本地存储
const saveSettings = () => {
  const settings = {
    notificationEnabled: notificationEnabled.value,
    selectedSound: selectedSound.value,
    volume: volume.value,
    vibrationEnabled: vibrationEnabled.value,
    browserNotificationEnabled: browserNotificationEnabled.value,
    requireConfirmation: requireConfirmation.value
  }
  localStorage.setItem('countdown-notification-settings', JSON.stringify(settings))
  
  // 更新原始设置和状态
  originalSettings.value = JSON.stringify(settings)
  settingsChanged.value = false
  
  // console.log('通知设置已保存:', settings)
}

// 重置为默认设置
const resetToDefaultSettings = () => {
  notificationEnabled.value = defaultSettings.notificationEnabled
  selectedSound.value = defaultSettings.selectedSound
  volume.value = defaultSettings.volume
  vibrationEnabled.value = defaultSettings.vibrationEnabled
  browserNotificationEnabled.value = defaultSettings.browserNotificationEnabled
  requireConfirmation.value = defaultSettings.requireConfirmation
  
  // 自动保存默认设置
  saveSettings()
  ElMessage.success('已重置为默认通知设置')
}

// 导出设置
const exportSettings = () => {
  const settings = {
    notificationEnabled: notificationEnabled.value,
    selectedSound: selectedSound.value,
    volume: volume.value,
    vibrationEnabled: vibrationEnabled.value,
    browserNotificationEnabled: browserNotificationEnabled.value,
    requireConfirmation: requireConfirmation.value,
    exportDate: new Date().toISOString()
  }
  
  const dataStr = JSON.stringify(settings, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  
  const link = document.createElement('a')
  link.href = URL.createObjectURL(dataBlob)
  link.download = `countdown-settings-${new Date().toISOString().split('T')[0]}.json`
  link.click()
  
  ElMessage.success('设置已导出')
}

// 导入设置
const importSettings = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.json'
  input.onchange = (event) => {
    const file = event.target.files[0]
    if (!file) return
    
    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const settings = JSON.parse(e.target.result)
        
        // 验证设置格式
        if (typeof settings.notificationEnabled === 'boolean' &&
            typeof settings.selectedSound === 'string' &&
            typeof settings.volume === 'number' &&
            typeof settings.vibrationEnabled === 'boolean' &&
            typeof settings.browserNotificationEnabled === 'boolean' &&
            typeof settings.requireConfirmation === 'boolean') {
          
          // 应用导入的设置
          notificationEnabled.value = settings.notificationEnabled
          selectedSound.value = settings.selectedSound
          volume.value = settings.volume
          vibrationEnabled.value = settings.vibrationEnabled
          browserNotificationEnabled.value = settings.browserNotificationEnabled
          requireConfirmation.value = settings.requireConfirmation
          
          // 自动保存
          saveSettings()
          ElMessage.success('设置导入成功')
        } else {
          ElMessage.error('设置文件格式无效')
        }
      } catch (error) {
        console.error('解析设置文件失败:', error)
        ElMessage.error('设置文件解析失败')
      }
    }
    reader.readAsText(file)
  }
  input.click()
}

// 取消更改
const cancelChanges = () => {
  if (!originalSettings.value) return
  
  try {
    const settings = JSON.parse(originalSettings.value)
    notificationEnabled.value = settings.notificationEnabled
    selectedSound.value = settings.selectedSound
    volume.value = settings.volume
    vibrationEnabled.value = settings.vibrationEnabled
    browserNotificationEnabled.value = settings.browserNotificationEnabled
    requireConfirmation.value = settings.requireConfirmation
    
    settingsChanged.value = false
    ElMessage.success('已取消更改，恢复上次保存的设置')
  } catch (error) {
    console.error('恢复设置失败:', error)
    ElMessage.error('恢复设置失败')
  }
}

// 监听设置变化，自动保存
watch(notificationEnabled, (newValue) => {
  checkSettingsChanged()
  saveSettings()
  // 如果禁用通知，停止当前播放的音频
  if (!newValue && currentAudio.value) {
    stopNotification()
  }
  ElMessage.success(`通知已${newValue ? '启用' : '禁用'}`)
})
watch(selectedSound, (newValue) => {
  checkSettingsChanged()
  saveSettings()
  // 如果当前有音频在播放，停止它
  if (currentAudio.value) {
    stopNotification()
  }
  if (newValue !== 'none') {
    ElMessage.success(`铃声已切换到: ${getSoundLabel(newValue)}`)
  }
})
watch(volume, (newValue) => {
  checkSettingsChanged()
  saveSettings()
  // 如果当前有音频在播放，立即应用新的音量设置
  if (currentAudio.value) {
    if (currentAudio.value.gainNode) {
      // Web Audio API
      currentAudio.value.gainNode.gain.value = newValue / 100
    } else if (currentAudio.value.audio && currentAudio.value.audio.volume !== undefined) {
      // HTML5 Audio
      currentAudio.value.audio.volume = newValue / 100
    }
  }
  ElMessage.success(`音量已设置为: ${newValue}%`)
})
watch(vibrationEnabled, (newValue) => {
  checkSettingsChanged()
  saveSettings()
  ElMessage.success(`振动已${newValue ? '启用' : '禁用'}`)
})
watch(browserNotificationEnabled, (newValue) => {
  checkSettingsChanged()
  saveSettings()
  if (newValue && 'Notification' in window && Notification.permission === 'default') {
    ElMessage.info('请允许浏览器通知权限以使用此功能')
  } else if (newValue) {
    ElMessage.success('浏览器通知已启用')
  } else {
    ElMessage.success('浏览器通知已禁用')
  }
})
watch(requireConfirmation, (newValue) => {
  checkSettingsChanged()
  saveSettings()
  if (newValue) {
    ElMessage.success('已启用确认模式：倒计时结束后需要手动确认')
  } else {
    ElMessage.success('已禁用确认模式：倒计时结束后自动保存记录')
  }
})

// 完成对话框状态
const showCompletionDialog = ref(false)
const currentAudio = ref(null)

// 导入计时器服务
import timerService from '../utils/timerService'

let countdownInstance = null

const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

const hasRecordedTime = computed(() => recordedTime.value > 0)



// 导入音频工具类
import { audioLoader, isHBuilderXApp } from '../utils/audioUtils'

// 预加载音频文件
const preloadAudio = async (soundType) => {
  if (soundType === 'none') return
  
  try {
    // 使用audioUtils进行预加载
    await audioLoader.preloadAudio(soundType)
  } catch (error) {
    console.error('预加载音频失败:', error)
  }
}

// 播放自定义铃声
const playCustomSound = async (soundType) => {
  if (soundType === 'none') return
  
  try {
    // 使用audioUtils播放音频，根据环境自动选择加载方式
    // App环境（5+ App）时使用HTML5 Audio加载，其他使用Web Audio API加载
    const audioResult = await audioLoader.playAudio(soundType, volume.value / 100, true)
    
    if (audioResult) {
      // 保存引用以便停止
      currentAudio.value = audioResult
    } else {
      throw new Error('音频播放失败')
    }
    
  } catch (error) {
    console.error('播放自定义铃声失败:', error)
    ElMessage.error('播放铃声失败')
  }
}



// 停止铃声
const stopNotification = () => {
  if (currentAudio.value) {
    try {
      // 使用audioUtils的stop方法停止音频
      if (currentAudio.value.stop) {
        currentAudio.value.stop()
      }
    } catch (error) {
      console.error('停止音频失败:', error)
    }
    currentAudio.value = null
  }
  
  // 停止振动
  stopVibration()
}

// 开始持续振动
const startVibration = () => {
  if (!vibrationEnabled.value || !('vibrate' in navigator) || isVibrating.value) {
    return
  }
  
  isVibrating.value = true
  // 持续振动模式：振动200ms，暂停100ms，循环
  const vibratePattern = [200, 100, 200, 100, 200]
  
  const vibrate = () => {
    if (isVibrating.value) {
      navigator.vibrate(vibratePattern)
      // 设置下一次振动
      vibrationInterval.value = setTimeout(vibrate, 500) // 500ms后再次振动
    }
  }
  
  // 开始第一次振动
  vibrate()
}

// 停止振动
const stopVibration = () => {
  if (isVibrating.value) {
    isVibrating.value = false
    if (vibrationInterval.value) {
      clearTimeout(vibrationInterval.value)
      vibrationInterval.value = null
    }
    // 停止当前振动
    if ('vibrate' in navigator) {
      navigator.vibrate(0)
    }
  }
}

// 播放铃声
const playNotification = async () => {
  if (!notificationEnabled.value || selectedSound.value === 'none') {
    return
  }
  
  try {
    // 播放音频
    await playCustomSound(selectedSound.value)
    
    // 开始持续振动通知
    startVibration()
    
    // 浏览器通知
    if (browserNotificationEnabled.value && 'Notification' in window && Notification.permission === 'granted') {
      new Notification('倒计时结束', { 
        body: '您设置的倒计时已经结束！',
        icon: '/favicon.ico',
        badge: '/favicon.ico',
        tag: 'countdown-notification'
      })
    }
    
    // 如果需要确认，显示对话框
    if (requireConfirmation.value) {
      showCompletionDialog.value = true
    } else {
      // 不需要确认，自动保存记录
      await autoSaveRecord()
    }
    
  } catch (error) {
    console.error('播放通知失败:', error)
  }
}

// 自动保存记录
const autoSaveRecord = async () => {
  if (recordedTime.value <= 0) return
  
  try {
    saving.value = true
    const today = dayjs().format('YYYY-MM-DD')
    await request.post('/timer/record', {
      date: today,
      duration: recordedTime.value,
      type: 'countdown'
    })
    ElMessage.success('记录已自动保存')
    recordedTime.value = 0
    await loadTodayTotal()
  } catch (error) {
    console.error('自动保存记录失败:', error)
    ElMessage.error('自动保存失败')
  } finally {
    saving.value = false
  }
  
  // 自动保存完成后停止振动
  stopVibration()
}

// 确认完成
const confirmCompletion = async () => {
  stopNotification()
  stopVibration() // 停止振动
  showCompletionDialog.value = false
  
  // 自动保存记录
  await autoSaveRecord()
}

// 测试通知
const testNotification = () => {
  if (selectedSound.value === 'none') {
    ElMessage.warning('当前设置为无声音，无法播放测试')
    return
  }
  
  // 先停止之前的振动（如果有）
  stopVibration()
  
  playNotification()
  ElMessage.success(`测试通知已播放 - ${getSoundLabel(selectedSound.value)}`)
  
  // 测试通知3秒后自动停止振动
  setTimeout(() => {
    stopVibration()
  }, 3000)
}

const startCountdown = () => {
  if (!isRunning.value && !isPaused.value && selectedDuration.value) {
    // 预加载音频文件（用户交互后）
    if (notificationEnabled.value && selectedSound.value !== 'none') {
      preloadAudio(selectedSound.value)
    }
    
    // 使用计时器服务创建倒计时
    countdownInstance = timerService.createCountdown({
      duration: selectedDuration.value,
      onUpdate: (remaining) => {
        displayTime.value = remaining
      },
      onComplete: () => {
        isRunning.value = false
        isPaused.value = false
        recordedTime.value = selectedDuration.value
        ElMessage.success('倒计时结束！')
        playNotification()
      },
      onStart: () => {
        isRunning.value = true
        isPaused.value = false
        displayTime.value = selectedDuration.value
      },
      onPause: () => {
        isRunning.value = false
        isPaused.value = true
      },
      onResume: () => {
        isRunning.value = true
        isPaused.value = false
      },
      onStop: () => {
        isRunning.value = false
        isPaused.value = false
      }
    })
    
    countdownInstance.start()
  }
}

const pauseCountdown = () => {
  if (isRunning.value && countdownInstance) {
    countdownInstance.pause()
  }
}

const resumeCountdown = () => {
  if (isPaused.value && countdownInstance) {
    countdownInstance.resume()
  }
}

const stopCountdown = () => {
  if (countdownInstance) {
    countdownInstance.stop()
    countdownInstance = null
  }
  isRunning.value = false
  isPaused.value = false
  recordedTime.value = selectedDuration.value - displayTime.value
  displayTime.value = 0
}

const resetCountdown = () => {
  if (countdownInstance) {
    countdownInstance.stop()
    countdownInstance = null
  }
  isRunning.value = false
  isPaused.value = false
  displayTime.value = 0
  recordedTime.value = 0
}

const saveRecord = async () => {
  if (recordedTime.value <= 0) {
    ElMessage.warning('没有可保存的记录')
    return
  }
  
  try {
    saving.value = true
    const today = dayjs().format('YYYY-MM-DD')
    await  request.post('/timer/record', {
      date: today,
      duration: recordedTime.value,
      type: 'countdown'
    })
    ElMessage.success('记录保存成功')
    recordedTime.value = 0
    await loadTodayTotal()
  } catch (error) {
    console.error('保存记录失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

const loadTodayTotal = async () => {
  try {
    const response = await  request.get('/timer/today/total')
    todayTotal.value = response.data.totalTime
  } catch (error) {
    console.error('获取今日总计失败:', error)
  }
}

const toggleNotificationSettings = () => {
  notificationSettingsExpanded.value = !notificationSettingsExpanded.value
}

onMounted(() => {
  loadTodayTotal()
  // 请求通知权限
  if ('Notification' in window && Notification.permission === 'default') {
    Notification.requestPermission()
  }
  
  // 从本地存储加载通知设置
  loadNotificationSettings()
  
  // 预加载音频文件（在用户交互后）
  if (notificationEnabled.value && selectedSound.value !== 'none') {
    // 延迟预加载，确保在用户交互后执行
    setTimeout(() => {
      preloadAudio(selectedSound.value)
    }, 1000)
  }
})

// 加载通知设置
const loadNotificationSettings = () => {
  const savedSettings = localStorage.getItem('countdown-notification-settings')
  if (savedSettings) {
    try {
      const settings = JSON.parse(savedSettings)
      // 使用默认值作为后备，确保所有设置都有值
      notificationEnabled.value = settings.notificationEnabled ?? defaultSettings.notificationEnabled
      selectedSound.value = settings.selectedSound ?? defaultSettings.selectedSound
      volume.value = settings.volume ?? defaultSettings.volume
      vibrationEnabled.value = settings.vibrationEnabled ?? defaultSettings.vibrationEnabled
      browserNotificationEnabled.value = settings.browserNotificationEnabled ?? defaultSettings.browserNotificationEnabled
      requireConfirmation.value = settings.requireConfirmation ?? defaultSettings.requireConfirmation
      
      // 设置原始设置用于比较
      originalSettings.value = JSON.stringify(settings)
      settingsChanged.value = false
      
      // console.log('通知设置已加载:', settings)
    } catch (error) {
      console.error('加载通知设置失败:', error)
      // 如果解析失败，使用默认设置
      resetToDefaultSettings()
    }
  } else {
    // 如果是第一次访问，保存默认设置
    saveSettings()
    ElMessage.success('欢迎使用倒计时！已为您设置默认通知选项')
  }
}

onUnmounted(() => {
  if (countdownInstance) {
    countdownInstance.stop()
    countdownInstance = null
  }
  
  // 停止铃声和振动
  stopNotification()
  stopVibration()
  
  // 使用audioUtils清理音频资源
  audioLoader.cleanup()
  
  // 设置已经在变化时自动保存，这里不需要重复保存
})
</script>

<style scoped>
.countdown-page {
  min-height: 100vh;
   background-color: var(--bg-primary);
}

.header {
  background: var(--header-bg);
  color: white;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  position: relative;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-center {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 12px;
  background: rgba(255, 255, 255, 0.1);
  padding: 8px 16px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.title-icon {
  font-size: 24px;
  color: #ffd700;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.2));
}

.page-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.back-btn {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  border-radius: 8px;
  font-weight: 500;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.countdown-status {
  display: flex;
  align-items: center;
  gap: 16px;
  background: rgba(255, 255, 255, 0.1);
  padding: 8px 16px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.status-tag {
  font-size: 14px;
  font-weight: 500;
  border: none;
  /* background: rgba(255, 255, 255, 0.2);
  color: white; */
}

.main {
  padding: 20px;
}

.countdown-card {
  max-width: 600px;
  margin: 0 auto 20px;
}

.countdown-display {
  text-align: center;
  padding: 20px;
}

.time-display {
  font-size: 48px;
  font-weight: bold;
  font-family: 'Courier New', monospace;
  color: #303133;
  margin-bottom: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.duration-selector {
  margin-bottom: 30px;
}

.countdown-controls {
  display: flex;
  justify-content: center;
  gap: 16px;
  flex-wrap: wrap;
}

/* 通知设置卡片样式 */
.notification-card {
  max-width: 600px;
  margin: 0 auto 20px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.notification-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 16px 16px 16px 16px;
  cursor: pointer; /* 添加鼠标指针样式 */
  transition: background-color 0.3s ease;
}

.card-header:hover {
  background: #f5f7fa;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 20px;
  color: #409eff;
  background: rgba(64, 158, 255, 0.1);
  padding: 8px;
  border-radius: 10px;
  transition: transform 0.3s ease; /* 添加旋转动画 */
}

.header-icon.rotated {
  transform: rotate(90deg); /* 展开时旋转 */
}

.card-header h4 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 16px;
}

.notification-switch {
  --el-switch-on-color: #67c23a;
}

.settings-status {
  font-size: 12px;
  padding: 6px 12px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.notification-settings {
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding: 20px;
  overflow: hidden;
  transition: all 0.3s ease;
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
    max-height: 0;
  }
  to {
    opacity: 1;
    transform: translateY(0);
    max-height: 1000px;
  }
}

.setting-section {
  background: #fafbfc;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.setting-section:hover {
  background: #f5f7fa;
  border-color: #c0c4cc;
  transform: translateY(-1px);
}

.section-title {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e4e7ed;
}

.section-icon {
  font-size: 18px;
  color: #409eff;
  background: rgba(64, 158, 255, 0.1);
  padding: 6px;
  border-radius: 8px;
}

.section-title span {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.setting-item {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.setting-item:last-child {
  margin-bottom: 0;
}

.setting-item label {
  font-weight: 600;
  color: #2c3e50;
  min-width: 100px;
  font-size: 14px;
}

.sound-select {
  min-width: 250px;
}

.volume-control {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
}

.volume-slider {
  flex: 1;
  max-width: 200px;
}

.volume-display {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 80px;
  justify-content: center;
}

.volume-display .el-icon {
  font-size: 18px;
  color: #409eff;
}

.volume-text {
  font-weight: 600;
  color: #409eff;
  font-size: 14px;
  min-width: 40px;
}

.checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.feature-checkbox {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.feature-checkbox:hover {
  background: rgba(64, 158, 255, 0.05);
}

.checkbox-icon {
  font-size: 16px;
  color: #409eff;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.button-row {
  display: flex;
  gap: 12px;
  justify-content: center;
  flex-wrap: wrap;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 100px;
  justify-content: center;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.record-card {
  max-width: 600px;
  margin: 0 auto;
}

.record-card h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.record-controls {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-bottom: 16px;
}

.today-total {
  text-align: center;
  padding: 12px;
  background-color: #f6ffed;
  border-radius: 6px;
  color: #52c41a;
  font-weight: 600;
}

/* 完成对话框样式 */
.completion-dialog ::v-deep .el-dialog {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.15);
}

.completion-dialog ::v-deep .el-dialog__header {
  background: linear-gradient(135deg, #67c23a 0%, #52c41a 100%);
  color: white;
  padding: 20px 24px;
  margin: 0;
}

.completion-dialog ::v-deep .el-dialog__title {
  color: white;
  font-weight: 600;
  font-size: 18px;
}

.completion-dialog ::v-deep .el-dialog__body {
  padding: 24px;
  background-color: var(--bg-primary);
}

.completion-content {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.completion-icon {
  animation: bellRing 1s ease-in-out infinite;
}

@keyframes bellRing {
  0%, 100% {
    transform: rotate(0deg);
  }
  25% {
    transform: rotate(10deg);
  }
  75% {
    transform: rotate(-10deg);
  }
}

.completion-message h3 {
  margin: 0 0 8px 0;
  color: var(--text-primary);
  font-size: 20px;
  font-weight: 600;
}

.completion-message p {
  margin: 0;
  color: var(--text-secondary);
  font-size: 14px;
}

.completion-actions {
  margin-top: 10px;
}

/* 移动端适配 */
@media (max-width: 768px) {
/* 仅 5+ App 环境生效（通过标记类精准控制） */
html.app-5plus .header {
  padding-top: var(--status-bar-height);
height: calc(55px + var(--status-bar-height));
}
   .header-content {
      /* 保持横向排列，不换行 */
      flex-direction: row; 
      padding: 10px 0;
      gap: 6px; /* 进一步缩小间距 */
      
    }

    .date-navigation {
      order: 0; /* 恢复默认顺序，不放在最上面 */
      gap: 6px;
    }

    /* 可选：如果按钮文字太长，可只保留图标（按需选择） */
    .header-content .el-button span {
      display: none; /* 隐藏按钮文字，只显示图标 */
     }

    .el-button {
      font-size: 11px;
      border-radius: 15px;
     }
    .record-controls-btn
     {
      font-size: 13px;
     }

     ::v-deep .el-dialog {
      width: 85%;
     }
  /* .header-content {
    flex-direction: column;
    gap: 10px;
    padding: 10px 0;
  }
  
  .date-navigation {
    order: -1;
  } */
  
  .main {
    padding: 10px;
  }
  
  .time-display {
    font-size: 60px;
  }
  
  .countdown-controls {
    flex-direction: row;
     gap: 10px;
    align-items: center;
  }
  
  .record-controls {
    flex-direction: row;
    align-items: center;
  }
  
  .notification-settings {
    gap: 16px;
    padding: 5px;
  }
  
  .setting-section {
    padding: 15px;
  }
  
  .setting-item {
    /* flex-direction: column; */
    align-items: flex-start;
    gap: 8px;
  }
  
  .setting-item label {
    min-width: auto;
  }
  
  .sound-select {
    min-width: 100%;
    width: 100%;
  }
  
  .volume-control {
    /* flex-direction: column;
    align-items: flex-start; */
    gap: 12px;
    transform: translateY(-15%);
  }
  
  .volume-slider {
    max-width: 100%;
    width: 100%;
  }
  
  .volume-display {
    justify-content: flex-start;
    min-width: auto;
  }
  
  .checkbox-group {
    gap: 8px;
  }
  
  .feature-checkbox {
    padding: 6px 8px;
  }
  
  .button-row {
    /* flex-direction: column; */
    gap: 8px;
  }
  
  .action-btn {
    /* min-width: 100%; */
    /* width: 100%; */
  }
  
  .header-controls {
    flex-direction: row;
    gap: 8px;
    align-items: flex-start;
  }
  
  .settings-status {
    font-size: 10px;
    padding: 4px 8px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .header-left {
    align-self: flex-start;
  }
  
  .completion-dialog ::v-deep .el-dialog {
    width: 90% !important;
    margin: 20px auto;
  }
  
  .completion-content {
    gap: 16px;
  }
  
  .completion-message h3 {
    font-size: 18px;
  }
  
  .completion-message p {
    font-size: 13px;
  }
}
</style> 